package com.chenyue.cm.controller;

import com.alibaba.fastjson.JSONObject;
import com.chenyue.cm.baidu.ueditor.ActionEnter;
import com.chenyue.cm.base.config.UeditorConfig;
import com.chenyue.cm.utils.DateUtils;
import com.chenyue.cm.utils.FileUtil;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/ueditor")
public class UeditorController {
	
	
	@Value("${lcmaster.upload.systemUploadPath}")
	private String systemUploadPath;
	
	/**
     * 获取Ueditor的配置文件
     * @return
	 * @throws IOException 
     */
//    @GetMapping("/config")
//    public String getConfig() {
//        return "{\n" +
//                "        \"imageActionName\": \"upload\",\n" +
//                "            \"imageFieldName\": \"file\",\n" +
//                "            \"imageMaxSize\": 2048000,\n" +
//                "            \"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
//                "        \"imageCompressEnable\": true,\n" +
//                "            \"imageCompressBorder\": 1600,\n" +
//                "            \"imageInsertAlign\": \"none\",\n" +
//                "            \"imageUrlPrefix\": \"\",\n" +
//                "            \"imagePathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
//                "\n" +
//                "        /* 上传文件配置 */\n" +
//                "        \"fileActionName\": \"uploadfile\",\n" +
//                "            \"fileFieldName\": \"file\",\n" +
//                "            \"filePathFormat\": \"/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
//                "            \"fileUrlPrefix\": \"\",\n" +
//                "            \"fileMaxSize\": 51200000,\n" +
//                "            \"fileAllowFiles\": [\n" +
//                "        \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
//                "                \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
//                "                \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
//                "                \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
//                "                \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"]\n" +
//                "    }";
//    }
    
    
    @RequestMapping("/config")
    @ResponseBody
    public void  ueditorConfig(HttpServletRequest request , HttpServletResponse response , String callback, String action ) throws IOException  {

    	response.setContentType("text/html; charset=UTF-8"); 
    	PrintWriter writer=response.getWriter();
    	
    	try {
    		switch (action) {
            case "config": // 此处即为获取配置文件的case
                String myresult = UeditorConfig.CONFIG.getConfigStr(callback);
        		writer.write(myresult);
        		writer.close();
            case "uploadimage":
            	
            	
//            	State state = null;
//            	state = new BaseState(true);
//        		state.putInfo( "size", "222" );
//        		state.putInfo( "title", "2222" );
//				state.putInfo("url", "http://127.0.0.1:4001/CM//upload/2019-12-31/2019-12-313787.jpg");
//				state.putInfo("type", "img");
//				state.putInfo("original", "xxxx.jpg");
//				writer.write(JSON.toJSONString(state));
//	            writer.close();
				
                //this.upload(request ,response );
                JSONObject json = new JSONObject();
                json.put("state","SUCCESS");
                json.put("success",true);
                json.put("original","1.jpg");
                json.put("size","1212");
                json.put("url","http://127.0.0.1:4001/CM//upload/2019-12-31/2019-12-313787.jpg");
                json.put("title", "222");
                json.put("type",".jpg");
                json.put("code", 0);
                writer.write(json.toString());
                writer.close();
        }
    		
		} catch (Exception e) {
			// TODO: handle exception
		}
 
    }
   
 
	
	@RequestMapping(value = "/config2")
	public void config(HttpServletRequest request, HttpServletResponse response) throws JSONException {
		response.setContentType("application/json");
		String rootPath = request.getSession().getServletContext().getRealPath("/");
		rootPath = ClassUtils.getDefaultClassLoader().getResource("").getPath();
		try {
			String exec = new ActionEnter(request, rootPath).exec();
			System.err.println( exec );
			//String exec = "";
			PrintWriter writer = response.getWriter();
			writer.write(exec);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	
//
//	@RequestMapping(value = "/config3")
//	public void config3(HttpServletRequest request, HttpServletResponse response  , String callback, String action  ) throws JSONException, IOException {
//		PrintWriter writer = response.getWriter();
//		switch (action) {
//		case "config": // 此处即为获取配置文件的case
//		    String myresult = UeditorConfig.CONFIG.getConfigStr(callback);
//			writer.write(myresult);
//			writer.close();
//		case "uploadimage":
//			String rootPath = request.getSession().getServletContext().getRealPath("/");
//			String rootPath1 = ClassUtils.getDefaultClassLoader().getResource("").getPath();
//			System.out.println(rootPath);
//			System.out.println(rootPath1);
//			String exec = new ActionEnter(request, rootPath1).exec();
//			System.out.println(exec);
//
//			writer.write(exec);
//			writer.flush();
//			writer.close();
//		}
//	}
//
	
	
    /**
	 * 文件上传
	 * 
	 * @param requst
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public Map<String, Object> upload(HttpServletRequest request, HttpServletResponse response) {
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		try {
			// 上传文件保存路径
			String uploadPath = systemUploadPath;
			String dateStr = DateUtils.getTodayStr();
			String descFileDir = uploadPath + "upload/" + dateStr;

			FileUtil.mkdirs(descFileDir);

			String dataString  = "";
			
			StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            Iterator<String> iterator = req.getFileNames();
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                String fileNames = file.getOriginalFilename();
                int split = fileNames.lastIndexOf(".");
	            //存储文件
	            //文件名  fileNames.substring(0,split)
	            //文件格式   fileNames.substring(split+1,fileNames.length())
	           //文件内容 file.getBytes()
               //file.getInputStream()
                
                String  newFileName = DateUtils.getTodayStr() + new Random().nextInt(10000) + fileNames.substring(fileNames.lastIndexOf("."), fileNames.length());
                InputStream is = file.getInputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				OutputStream out = new FileOutputStream(descFileDir + "/" + newFileName);
				while ((len = is.read(buffer)) != -1) {
					out.write(buffer, 0, len);
				}
				out.close();
				is.close();
				dataString =  "/upload/" + dateStr + "/" + newFileName;
           }
            resultMap.put("state", "success");
            resultMap.put("path", dataString );
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("state", "fail");
		}
		
		return resultMap;
		
	}
	
}
